import {Component, OnInit, ViewChild} from '@angular/core';
import {DynamicComponent, DynamicComponentEvent, MessageService, ModalComponent, PaginationService, Table} from '../../../../../ng-tools';
import {TicketService} from '../../../../services/api/ticket.service';
import {Router} from '@angular/router';
import {HttpParams} from '@angular/common/http';
import {UserAccountDetailService} from '../../../../services/formatter/user-account-detail.service';

@Component({
  selector: 'account-detail',
  templateUrl: './account-detail.component.html',
  styleUrls: ['./account-detail.component.scss']
})
export class AccountDetailComponent implements OnInit, DynamicComponent {
  @ViewChild('modal') private modal: ModalComponent;
  context: any;
  dynamic: true;
  events: DynamicComponentEvent;
  page = 1;
  currentUser;
  set data(value) {
    this.currentUser = value;
  }
  pagenation = new PaginationService(null, null);
  moneyTable = new Table({
    headers: this.userAccountDetail.formatter,
  });

  constructor(private message: MessageService,
              private ticketService: TicketService,
              private router: Router,
              private userAccountDetail: UserAccountDetailService) {
  }

  ngOnInit() {
    this.getInfo(1);
  }
  getInfo(page) {
    this.pagenation.simpleFormatter = this.moneyTable.options.headers;
    this.ticketService.get(this.ticketService.urls.getUserOrderInfo, {
      observe: 'response',
      params: new HttpParams()
          .append('web_token', localStorage.getItem('token'))
          .append('userId', this.currentUser.userUid)
          .append('pageNum', page + '')
          .append('pageSize', '10')}).subscribe((resp) => {
      if (resp.body.success) {
        const result = resp.body.returnValue.page;
        this.pagenation.page.results = result.list;
        this.pagenation.page.totalPage = result.pages;
        this.pagenation.page.pageNumber = result.pageNum;
        this.pagenation.formatData();
        this.message.sendMessage('page load progress', this);
      } else {
        this.router.navigateByUrl('/login').catch();
      }
    });
  }
  firstPage() {
    this.page = 1;
    this.getInfo(1);
  }
  previousPage() {
    if (this.page > 1) {
      this.page = this.page - 1;
    } else {
      this.page = 1;
    }
    this.getInfo(this.page);
  }
  nextPage() {
    if (this.page < this.pagenation.page.totalPage) {
      this.page = this.page + 1;
    } else {
      this.page = this.pagenation.page.totalPage;
    }
    this.getInfo(this.page);
  }
  lastPage() {
    this.page = this.pagenation.page.totalPage;
    this.getInfo(this.pagenation.page.totalPage);
  }

}
